<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Models\Pictuer;
use App\Transformers\PictuerTransformer;
use App\Transformers\TagTransformer;
use App\Models\Tag;
use App\Models\Category;
class PictuersController extends Controller
{
    public function index(Request $request, Pictuer $pictuer, Tag $tag)
    {
        $query = $pictuer->query();
        $page_limit = $request->page_limit ?: 30;
        $pages = 0;
        //$tag = [];
        $pictuers = $pictuer->with('likes')->filter($request->all())->latest()->paginate($page_limit);

        /*switch ($request->order) {
            case 'recent':
                $query->recent();
                break;

            default:
                $query->orderBy('id', 'desc');
                break;
        }
        if($request->name) {
            if($tag = Tag::where('url', $request->name)->first())
            {
                $pictuers = $query->whereHas('tags', function ($q) use ($tag) {
                    $q->where('url', $tag->url);
                })->with('tags')->orderBy('title')->paginate($page_limit);
            } else {
                $pictuers = $query->paginate($page_limit);
            }
        } else {
            $pictuers = $query->paginate($page_limit);
        }*/
        $category_name = $request->input('category', 'touxiang');
        if ($category_name == 'all') {
          $category = Category::where('slug', 'touxiang')->first();
        } else {
          $category = Category::where('slug', $category_name)->first();
        }
        $hot_tags = $tag->getHotTags($category->id);
        $base_colors = \DB::table('color_averages')->selectRaw('COUNT(*) AS count, basecolor')->groupBy('basecolor')->orderBy('count', 'desc')->get();
        $base_colors->map(function($item) {
          return $item->name = $this->colorName($item->basecolor);
        });
        return $this->response->paginator($pictuers, new PictuerTransformer())
          ->addMeta('hot_tags', $hot_tags)
          ->addMeta('tag', $tag)
          ->addMeta('user', $this->user())
          ->addMeta('colors', $base_colors);
    }
    private function colorName($color)
    {
      $colors = [
        'DE2020' => '红色',
        'FE6C00' => '橙色',
        'FEBF00' => '黄色',
        '59A725' => '绿色',
        '892BCF' => '紫色',
        'D744BA' => '粉色',
        '06B7C8' => '青色',
        '0065FE' => '蓝色',
        '733413' => '棕色',
        'ffffff' => '白色',
        '000000' => '黑色'
      ];
      return $colors[$color];
    }
}
